from fastapi.routing import APIRouter


from fastapi import APIRouter, Depends, HTTPException, status, Query
from sqlalchemy.orm import Session
from typing import List, Optional
from uuid import UUID

from app.database.base import get_db
from app.schemas.device import DeviceCreate, DeviceUpdate, DeviceResponse
from app.services.device import DeviceService
from app.core.auth import get_current_user
from app.models.user import User

router: APIRouter = APIRouter(prefix="/devices", tags=["devices"])
device_service = DeviceService()

@router.post("/", response_model=DeviceResponse, status_code=status.HTTP_201_CREATED)
async def create_device(
    device_data: DeviceCreate,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_user)
):
    """创建设备"""
    device_data_dict = device_data.model_dump()
    device_data_dict["owner_id"] = current_user.id
    return device_service.create(db, obj_in=device_data)

@router.get("/", response_model=List[DeviceResponse])
async def get_devices(
    skip: int = Query(0, ge=0),
    limit: int = Query(100, ge=1, le=1000),
    device_type: Optional[str] = None,
    status: Optional[str] = None,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_user)
):
    """获取设备列表"""
    filters = {}
    if device_type:
        filters["device_type"] = device_type
    if status:
        filters["status"] = status
    
    return device_service.get_multi(db, skip=skip, limit=limit, filters=filters)

@router.get("/{device_id}", response_model=DeviceResponse)
async def get_device(
    device_id: UUID,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_user)
):
    """获取设备详情"""
    device = device_service.get(db, device_id)
    if not device:
        raise HTTPException(status_code=404, detail="设备不存在")
    return device

@router.put("/{device_id}", response_model=DeviceResponse)
async def update_device(
    device_id: UUID,
    device_data: DeviceUpdate,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_user)
):
    """更新设备"""
    device = device_service.get(db, device_id)
    if not device:
        raise HTTPException(status_code=404, detail="设备不存在")
    
    return device_service.update(db, db_obj=device, obj_in=device_data)

@router.delete("/{device_id}")
async def delete_device(
    device_id: UUID,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_user)
):
    """删除设备"""
    device = device_service.remove(db, id=device_id)
    if not device:
        raise HTTPException(status_code=404, detail="设备不存在")
    
    return {"message": "设备删除成功"}